<script>
import axios from 'axios'
export default{
  data(){
    return{
      username: '',
      password: '',
      code: '',
      validCode: ''
    }
  },
  created(){
    this.getCode()
  },
  methods:{
    getCode(){
      this.validCode = ''
      var _this = this;
      axios.post("http://127.0.0.1:3000/getCode")
          .then(res => {
              console.log(res.data)
              _this.code = res.data
          })
    },
    onSubmit(values){
      if(this.validCode == this.code){
        axios.post("http://127.0.0.1:3000/login", values)
          .then(res => {
            if(res.data == 'success'){
              showSuccessToast('登录成功');
            }else if(res.data == 'failed'){
              showFailToast('用户名或密码错误');
              this.getCode()
            }
          })
      }else{
        showToast({
          message: '验证码错误',
          icon: 'cross',
        });
        this.getCode()
      }
    }
  }
}
</script>

<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model="username"
        name="username"
        label="用户名"
        placeholder="请输入用户名"
        :rules="[{ required: true, message: '用户名不能为空' }]"
      />
      <van-field
        v-model="password"
        name="password"
        type="password"
        label="密码"
        placeholder="请输入密码"
        :rules="[{ required: true, message: '密码不能为空' }]"
      />
      <van-field
        v-model="validCode"
        center
        clearable
        label="验证码"
        placeholder="请输入验证码"
      >
        <template #button>
          <van-button size="small" type="primary">{{ code }}</van-button>
        </template>
      </van-field>
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>

</template>

<style scoped>

</style>
